package com.astro.app;

import java.io.File;
import java.io.InputStream;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Scanner;

import com.checkfree.isolutions.customer.persist.Account;
import com.checkfree.isolutions.customer.persist.AccountHomeImpl;
import com.checkfree.isolutions.customer.persist.Merchant;
import com.checkfree.isolutions.customer.persist.MerchantHome;
import com.checkfree.isolutions.customer.persist.MerchantHomeImpl;
import com.checkfree.isolutions.persist.PersistServer;

public class LoadAccount {
	
	static final String CONFIG_FILE = "/properties/LoadAccount.properties";
	static final java.util.Properties appCfg = new java.util.Properties();
	
	static final SimpleDateFormat dateFormatter = new SimpleDateFormat("yyyyMMdd");
	private String data_path = "";
	private String data_backup_path = "";

	public static void main(String[] args) {
		System.out.println("BEGIN");
		new LoadAccount().createAccounts();
		System.out.println("FINISH!!!");
	}
	
	public LoadAccount() {
        try {
            InputStream stream = this.getClass().getResourceAsStream(CONFIG_FILE);
            if (stream != null){
                appCfg.load(stream);
            }else{
                throw new Exception("LoadAccount.properties Input Stream is null");
			}
        } catch (Exception e) {
            e.printStackTrace();
        }	
        data_path = appCfg.getProperty("data.path");
        data_backup_path = appCfg.getProperty("data.backup.path");

	}
	
	public void createAccounts() {

		String merchant = "ASTRO";
		try {
			PersistServer.activate(merchant);
			PersistServer.beginTransaction();
	
			Merchant theMerchant = MerchantHomeImpl.singleton().findByName(merchant);
	        if (theMerchant == null) {
	            throw new Exception("unable to obtain Persist Merchant object");
			}
	        Account account = null;
	        
	        // loop file here
	        File dataDir = new File(data_path);
	        
	        if (dataDir != null && dataDir.list() != null && dataDir.list().length > 0) {
	        	String[] files = dataDir.list();
	        	for (int i = 0; i < files.length; i++) {

					Scanner scanner = new Scanner(new File(data_path + File.separator + files[i]));
					System.out.println("=======================================");
					System.out.println("Start Processing file : " + files[i]);
					int count = 0;
					int countNew = 0;
					while (scanner.hasNextLine()) {
						count ++;
						String accountNo = scanner.nextLine();
						
				        account = AccountHomeImpl.singleton().findByExternalKeyAndMerchant(accountNo.trim(), theMerchant);
				        if (account == null) {
				        	
				        	countNew ++;
				        	account = AccountHomeImpl.singleton().create(accountNo, getUserRealm(merchant));
				        	account.setType("A");
				            account.setStatementRetention(372);
				            System.out.println("	" + accountNo + " is created new");
						} else {
							System.out.println("	" + accountNo + " is existed");
						}
					}
					System.out.println("End Processing file : " + files[i] + "; Total accounts = " + count + " ( new " + countNew + ")");
					scanner.close();
		
					// move file
					moveFile(data_path + File.separator + files[i], data_backup_path);
					
				}
	        	
	        }
			
		} catch (Throwable e) {
			e.printStackTrace();
		} finally {
			PersistServer.commitTransaction();
			PersistServer.deactivate();
		}
	}

	public void moveFile(String filePath, String destination) {
		try {
				Calendar cal = Calendar.getInstance();
				File a = new File(filePath);
				String FileName = a.getName();
		
				String tempDate = dateFormatter.format(cal.getTime()).toString();
		
				String strTempFolder=destination+tempDate+File.separator;
		
				File DestiFolder = new File(strTempFolder);
		
				if (DestiFolder.exists()){
		
					boolean i = a.renameTo(new File(strTempFolder+FileName));
					System.out.println("Move Sucessful " + i);
		
				}else{
		
					boolean j = DestiFolder.mkdirs();
					System.out.println("make dir Successful " + j);
					boolean i = a.renameTo(new File(strTempFolder+FileName));
					System.out.println("Move Sucessful " + i);
		
				}
		} catch (Exception e) {
			e.printStackTrace();
		}
}


	public Merchant getUserRealm(String mer) throws Exception, Throwable {
		// Get the organization
		MerchantHome merchantHome = MerchantHomeImpl.singleton();
		Merchant merchant = merchantHome.findByName(mer);
		return merchant;
	}
}

